package com.hushao.aimi.service.impl;

import com.hushao.aimi.DateUtil;
import com.hushao.aimi.ImagesUtil;
import com.hushao.aimi.common.PageVo;
import com.hushao.aimi.common.ResponseCode;
import com.hushao.aimi.common.ServerResponse;
import com.hushao.aimi.entity.AimiCategory;
import com.hushao.aimi.entity.AimiProduct;
import com.hushao.aimi.entity.AimiProductSpec;
import com.hushao.aimi.repository.CategoryRepository;
import com.hushao.aimi.repository.ProductRepository;
import com.hushao.aimi.repository.ProductSpecRepository;
import com.hushao.aimi.service.ProductService;
import com.hushao.aimi.vo.ProductSpecVo;
import com.hushao.aimi.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @description: 商品业务
 * @author: 胡少
 * @create: 2018-06-06 15:28
 **/
@Service
@Slf4j
public class ProductServiceImpl implements ProductService {


    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private ProductSpecRepository productSpecRepository;

    @Autowired
    private CategoryRepository categoryRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServerResponse addProduct(AimiProduct product) throws Exception {
        if (product!=null){
            if (product.getId()!=null){
                productRepository.save(product);
                log.info("更新商品成功");
                return ServerResponse.Success("更新商品成功");
            }else {
                productRepository.save(product);
                log.info("新增商品成功");
                return ServerResponse.Success("新增商品成功");
            }
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServerResponse updateProductStatus(Integer productId, Integer status) throws Exception {
        if (productId==null||status==null){
            log.error("修改商品状态错误");
            return ServerResponse.Error(ResponseCode.BAD_REQUEST.getCode(),ResponseCode.BAD_REQUEST.getDesc());
        }
        int rowCount=productRepository.updateStatus(productId,status);
        if(rowCount>0){
            log.info("修改商品状态成功！id:{}",productId);
            return ServerResponse.Success("修改商品状态成功！");
        }
        return ServerResponse.Error("修改商品状态失败！");
    }

    @Override
    public ServerResponse productDetail(String productId) {
        Optional<AimiProduct> optional=productRepository.findById(productId);
        if(optional.isPresent()){
            log.error("无此商品id:{}",productId);
            return  ServerResponse.Error("无此商品");
        }
        AimiProduct product=optional.get();

        //查询该商品的规格
        List<AimiProductSpec> productSpecs=productSpecRepository.findByProductId(productId);


        return ServerResponse.Success();
    }

    @Override
    public ServerResponse getProductByNameLike(String name, Pageable pageable) {
        name="%"+name+"%";
        Page<AimiProduct> page=productRepository.findByNameLike(name,pageable);
        List<ProductVo> productVos=new LinkedList<>();

        //查询子分类
        List<AimiCategory> optional=categoryRepository.findByParentIdNot(0);

        for (AimiProduct ap:page.getContent()){
           //普通图片
           List<String> subImages=ImagesUtil.segmentationImages(ap.getSubImages(),";");
           //规格
          List<ProductSpecVo> productSpecVos=productSpecRepository.findByProductId(ap.getId()).stream()
                  .map(apc-> new ProductSpecVo(apc.getId(),apc.getName(),apc.getImage(),apc.getPrice(),apc.getStock()))
                  .collect(Collectors.toList());
          Optional<AimiCategory> category=optional.parallelStream().filter(o->o.getId().equals(ap.getCategoryId())).findAny();
           ProductVo productVo=new ProductVo(ap.getId(),
                   new Integer[] {category.get().getParentId(),category.get().getId()},
                   category.get().getName(),
                   ap.getProductCode(),
                   ap.getName(),
                   ap.getSubtitle(),
                   subImages,
                   ImagesUtil.segmentationImages(ap.getDetail(),";"),
                   ap.getSortOrder(),
                   ap.getStatus(),
                   productSpecVos,
                   DateUtil.getDateTimeOfTimestamp(ap.getCreateTime()),
                   DateUtil.getDateTimeOfTimestamp(ap.getUpdateTime()),
                   ap.getComment());
           productVos.add(productVo);
        }
        Map<String,Object> map=new HashMap<>(2);
        PageVo pageVo=new PageVo(page);
        map.put("page",pageVo);
        map.put("products",productVos);
        return ServerResponse.Success(map);
    }

    @Override
    public Long count() {
        return productRepository.count();
    }

    @Override
    public Optional<AimiProduct> getProductCode(String productCode) {
        return productRepository.findByProductCode(productCode);
    }


}
